package com.thm.tfast.core.sevruity.domain;

import com.thm.tfast.core.enums.StatusEnum;
import com.thm.tfast.modules.sys.model.SysUser;
import com.thm.tfast.modules.sys.model.vo.permission.PermissionVo;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName SysUserDetails
 * @Author THM
 * @Date 2022/10/10 15:08
 * @Version 1.0
 * @Description SpringSecurity需要的用户详情
 */
public class SysUserDetails implements UserDetails {
    /**
     * 用户信息
     */
    private SysUser sysUser;
    /**
     * 用户权限信息
     */
    private List<PermissionVo> permissions;
    /**
     * 时间
     */
    private Date date;

    public SysUserDetails(SysUser sysUser, List<PermissionVo> permissions) {
        this.sysUser = sysUser;
        this.permissions = permissions;
        this.date = new Date();
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //返回当前用户角色信息
        return permissions
                .stream()
                .map(SysPermission -> new SimpleGrantedAuthority(SysPermission.getPermission()))
                .collect(Collectors.toList());
    }

    @Override
    public String getUsername() {
        return sysUser.getUserName();
    }

    @Override
    public String getPassword() {
        return sysUser.getPassword();
    }

    public Long getUserId(){
        return sysUser.getId();
    }

    public Date getDate(){
        return date;
    }

    public SysUser getSysUser() {
        return sysUser;
    }

    public List<PermissionVo> getPermissions() {
        return permissions;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return Objects.equals(sysUser.getStatus(), StatusEnum.ENABLE.getCode());
    }
}
